﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using Newtonsoft.Json;
using WeChat.JsSDK.lib;
using WeChat.Common2;
using WeChat.Common;
using WeChat.JsSDK;
using System.Xml;
using System.Threading;
using Models;
using BLL;

namespace WeChat.HyfPay.Hyflib
{
    public class HyfPayApi
    {
        //生成订单传递json格式参数
        public static string unifiedorder(string Type, string merchOrderNo,string goodsName, string amount, string remark,string open)
        {
            JObject jo = new JObject();
            jo.Add("version", HyfConfig.version);                //协议版本
            jo.Add("organNo", HyfConfig.organNo);                //机构号
            jo.Add("hicardMerchNo", HyfConfig.hicardMerchNo);    //汇耘富商户号
            jo.Add("payType", Type);                             //支付类型
            jo.Add("backEndUrl", Config.ReUrls);                 //后台回调URL
            jo.Add("goodsName", goodsName);                    //商品名称
            jo.Add("merchOrderNo", merchOrderNo);                //商户订单号
            amount = (Double.Parse(amount) * 100).ToString();
            jo.Add("amount", amount);                            //交易金额
            if (Type == "014")
            {
                jo.Add("subAppId", GetSdkParams.getAppId());                              //子商户公众号id
                jo.Add("openId", open);                          //用户标识,微信公众号支付使用
            }

            jo.Add("remark", remark);                            //用户卡号
           
            jo.Add("customerName", "");                          //持卡人姓名
            jo.Add("certsNo", "");                               //身份证号
            jo.Add("frontEndUrl", "");                           //前台回调URL
            jo.Add("isT0", "");                                  //是否T0入账
            jo.Add("reserved", "");                              //预留域
            string sign = toSign(exChange(jo));
            jo.Add("sign", sign);                                //签名
            return jo.ToString();
        }


        /// <summary>
        ///  调用生成订单的参数发送post请求获得返回结果
        /// </summary>
        /// <param name="merchOrderNo">商户订单号</param>
        /// <param name="amount">金额</param>
        /// <param name="remark">用户卡号</param>
        /// <returns></returns>
        public static string getUnifiedOrder(string Type, string merchOrderNo, string goodsName,string amount, string remark,string open)
        {
            GetReturnJson gr = new GetReturnJson();
            
            string url = " https://www.icloudful.com/hicardpay/order/create";
            string json = unifiedorder(Type,merchOrderNo, goodsName, amount, remark, open);
            ApplicationLog.Write("汇耘富支付下单生成json："+json);
            var start = DateTime.Now;
            string response = gr.postReturnJson(url,json);
            ApplicationLog.Write("汇耘富支付下单后得到返回结果：" + response);
            var end = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);
            return response;
        }

        /// <summary>
        /// 对下单返回结果解析得到支付二维码字符串
        /// </summary>
        /// <param name="Type">支付类型009为支付宝，011为微信</param>
        /// <param name="merchOrderNo">商户自定义订单号</param>
        /// <param name="amount">交易金额</param>
        /// <param name="remark">用户卡号</param>
        /// <returns></returns>
        public static string getResult(string Type,string merchOrderNo,string goodsName, string amount,string remark,string open)
        {
            string responce = getUnifiedOrder(Type,merchOrderNo, goodsName, amount, remark, open);
            string qrURL = "";
             JObject jo = JObject.Parse(responce);
            string respCode = jo["respCode"].ToString();
            if (respCode=="00")
            {
                if (Type == "014")
                {
                    qrURL = responce;
                    ApplicationLog.Write("qrURL：" + qrURL);
                }
                else {
               qrURL = jo["qrURL"].ToString();
                 
                }
            }
            return qrURL;
        }



        //反扫
        /// <summary>
        /// 刷卡支付下单
        /// </summary>
        /// <param name="cardID"></param>
        /// <param name="money"></param>
        /// <param name="attachs"></param>
        /// <param name="order_No"></param>
        /// <param name="auth_codes"></param>
        /// <returns></returns>
        public static string micropay(string Type, string order_No, string goodsName, string amount, string cardID, string authCode)
        {
            JObject jo = new JObject();
            jo.Add("version", HyfConfig.version);                //协议版本
            jo.Add("organNo", HyfConfig.organNo);                //机构号
            jo.Add("hicardMerchNo", HyfConfig.hicardMerchNo);    //汇耘富商户号
            jo.Add("payType", Type);                             //支付类型
            jo.Add("goodsName", goodsName);                    //商品名称
            jo.Add("merchOrderNo", order_No);                //商户订单号
            amount = (Double.Parse(amount) * 100).ToString();
            jo.Add("amount", amount);                            //交易金额
            jo.Add("remark", cardID);                            //用户卡号
            jo.Add("authCode", authCode);                              //授权码
            jo.Add("backEndUrl", "");                           //后台回调URL
            jo.Add("isT0", "");                                  //是否T0入账
            string sign = toSign(exChange(jo));
            jo.Add("sign", sign);                                //签名
            return jo.ToString();
        }
        //调用下单的参数发送post请求获得返回结果
        public static string getMicropay(string Type, string order_No, string goodsName, string amount, string cardID, string authCode)
        {
            GetReturnJson gr = new GetReturnJson();
            string url = " https://www.icloudful.com/hicardpay/order/unScan";
            string json = micropay(Type, order_No, goodsName, amount.ToString(), cardID, authCode);
            ApplicationLog.Write("汇耘富支付下单生成json：" + json);
            var start = DateTime.Now;
            string response = gr.postReturnJson(url, json);
            ApplicationLog.Write("汇耘富支付下单后得到返回结果：" + response);
            var end = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);
            return response;
        }
        //对下单返回结果解析
        public static void ReverseApi(object o)
        {
            var obj = o as HyfParameter;
            string responce = getMicropay(obj.Type, obj.order_No, obj.goodsName, obj.amount.ToString(), obj.cardID, obj.authCode);

            JObject jo = JObject.Parse(responce);
            string respCode = jo["respCode"].ToString();
            if (respCode == "00")
            {
                ApplicationLog.Write("qrURL：" + responce);
                HyfResultOrder ho = new HyfResultOrder();
                ho.version = jo["version"].ToString();
                ho.hicardMerchNo = jo["hicardMerchNo"].ToString();//商户号
                ho.merchOrderNo = jo["merchOrderNo"].ToString();//商户订单号        
                ho.payType = jo["payType"].ToString();//支付类型
                ho.amount = (Double.Parse(jo["amount"].ToString()) / 100).ToString();//支付金额
                ho.hicardOrderNo = jo["hicardOrderNo"].ToString();//汇耘富支付订单号
                ho.createTime = jo["createTime"].ToString();//订单生成时间
                ho.payTime = jo["payTime"].ToString();//支付时间
                ho.cardno = "";//卡号
                ho.respCode = jo["respCode"].ToString();//返回码
                ho.respMsg = jo["respMsg"].ToString();//返回码说明
                ho.buyerId = "";//用户标识
                ho.isCredit = "";//借贷标识
                ho.channelOrderNo = "";//渠道订单号
                ho.sign = jo["sign"].ToString();//签名
                int i = HyfAddBLL.addRecord(ho);
              
            }
            else
            {
               // return "失败";
            }
        }
        //public static string ReverseApi(string Type, string  order_No, string goodsName, string amount, string cardID,string authCode)
        //{
        //    string responce = getMicropay(Type, order_No, goodsName, amount.ToString(), cardID, authCode);

        //    JObject jo = JObject.Parse(responce);
        //    string respCode = jo["respCode"].ToString();
        //    if (respCode == "00")
        //    {
        //        ApplicationLog.Write("qrURL：" + responce);
        //        HyfResultOrder ho = new HyfResultOrder();
        //        ho.version = jo["version"].ToString();
        //        ho.hicardMerchNo = jo["hicardMerchNo"].ToString();//商户号
        //        ho.merchOrderNo = jo["merchOrderNo"].ToString();//商户订单号        
        //        ho.payType = jo["payType"].ToString();//支付类型
        //        ho.amount = (Double.Parse(jo["amount"].ToString()) / 100).ToString();//支付金额
        //        ho.hicardOrderNo = jo["hicardOrderNo"].ToString();//汇耘富支付订单号
        //        ho.createTime = jo["createTime"].ToString();//订单生成时间
        //        ho.payTime = jo["payTime"].ToString();//支付时间
        //        ho.cardno ="";//卡号
        //        ho.respCode = jo["respCode"].ToString();//返回码
        //        ho.respMsg = jo["respMsg"].ToString();//返回码说明
        //        ho.buyerId ="";//用户标识
        //        ho.isCredit = "";//借贷标识
        //        ho.channelOrderNo = "";//渠道订单号
        //        ho.sign = jo["sign"].ToString();//签名
        //        int i = HyfAddBLL.addRecord(ho);
        //        if (i > 0)
        //        {
        //            return "成功";
        //        }
        //        else {
        //            return "失败";
        //        }
        //    }
        //    else {
        //        return "失败";
        //    }


        //}


        //将json类型转换成字典类型
        public static SortedDictionary<string, object> exChange(JObject jo)
        {       
            SortedDictionary<string, object> sd =JsonConvert.DeserializeObject<SortedDictionary<string, object>>(jo.ToString());
        
            return sd;
        }

        //生成签名
        public static string toSign(SortedDictionary<string, object> sd)
        {
            //排序生成签名返回新string
            string buff = "";
            foreach (KeyValuePair<string, object> pair in sd)
            {
                if (pair.Value == null)
                {
                 
                }

                if (pair.Key != "sign" && pair.Value.ToString() != "")
                {
                    buff += pair.Key + "=" + pair.Value + "&";
                }
            }
            buff = buff.Trim('&');

            //在string后加入API KEY
            buff += "&" + HyfConfig.Key;
            //MD5加密
            var md5 = MD5.Create();
            var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(buff));
            var sb = new StringBuilder();
            foreach (byte b in bs)
            {
                sb.Append(b.ToString("x2"));
            }
            return sb.ToString();
        }
    }
}